package com.ktgj.customer.controller;

import cn.hutool.core.codec.Base64Decoder;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.utils.xml.XElement;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.Insurance.heydayModel.HeydayCallback;
import com.ktgj.customer.domain.vo.HeydayVo;
import com.ktgj.customer.mapper.AssistProductMapper;
import com.ktgj.customer.mapper.CustomerMapper;
import com.ktgj.customer.mapper.InsuranceRecordMapper;
import com.ktgj.customer.mapper.InsuranceTypeMapper;
import com.ktgj.customer.service.ICardPurchaseService;
import com.ktgj.customer.service.IFinanceOrderRefundmentService;
import com.ktgj.flight.api.RemoteFlightService;
import com.ktgj.flight.api.domain.FlightOrderInfo;
import com.ktgj.pay.api.RemotePayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@ControllerAdvice
@RestController
@RequestMapping("/callback")
public class CallbackController {

    @Autowired
    private ICardPurchaseService cardPurchaseService;
    @Autowired
    private RemotePayService payService;
    @Autowired
    private IFinanceOrderRefundmentService financeOrderRefundmentService;
    @Autowired
    private RemoteFlightService remoteFlightService;
    @Autowired
    private InsuranceRecordMapper insuranceRecordMapper;
    @Autowired
    private AssistProductMapper assistProductMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private InsuranceTypeMapper insuranceTypeMapper;

    /**
     * crm购卡电话语音支付回调
     */
    @RequestMapping("/cardVoicePayCallback")
    public void cardVoicePayCallback(HttpServletResponse response, HttpServletRequest request) {
        PhoneSoundCallback phoneSoundCallback = new PhoneSoundCallback();
        try {
            request.setCharacterEncoding("UTF-8");
//            response_xml=String(Base64Decode(UrlDecode(request.getParameter(response_text),UTF-8)),UTF-8)
            String response_xml = Base64Decoder.decodeStr(request.getParameter("response_text"));
            XElement root = XElement.loadXml(response_xml);
            phoneSoundCallback.setAccountType(root.element("AccountType").getValue());
            phoneSoundCallback.setAcqSsn(root.element("AcqSsn").getValue());
            phoneSoundCallback.setAmount(root.element("Amount").getValue());
            phoneSoundCallback.setAsynAddress(root.element("AsynAddress").getValue());
            phoneSoundCallback.setCurrency(root.element("Currency").getValue());
            phoneSoundCallback.setDescription(root.element("Description").getValue());
            phoneSoundCallback.setMAC(root.element("MAC").getValue());
            phoneSoundCallback.setMerchantNo(root.element("MerchantNo").getValue());
            phoneSoundCallback.setMerchantOrderNo(root.element("MerchantOrderNo").getValue());
            phoneSoundCallback.setMethod(root.element("Method").getValue());
            phoneSoundCallback.setOrderNo(root.element("OrderNo").getValue());
            phoneSoundCallback.setOrderState(root.element("OrderState").getValue());
            phoneSoundCallback.setOrderType(root.element("OrderType").getValue());
            phoneSoundCallback.setProcCode(root.element("ProcCode").getValue());
            phoneSoundCallback.setProcessCode(root.element("ProcessCode").getValue());
            phoneSoundCallback.setRemark(root.element("Remark").getValue());
            phoneSoundCallback.setRespCode(root.element("RespCode").getValue());
            phoneSoundCallback.setSettleDate(root.element("SettleDate").getValue());
            phoneSoundCallback.setTerminalNo(root.element("TerminalNo").getValue());
            phoneSoundCallback.setTsNo(root.element("TsNo").getValue());
            phoneSoundCallback.setUpsNo(root.element("UpsNo").getValue());
            phoneSoundCallback.setUserPayedTime(root.element("UserPayedTime").getValue());
            phoneSoundCallback.setVersion(root.element("Version").getValue());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (phoneSoundCallback.getRespCode().equals("0000")) {//交易成功
            cardPurchaseService.cardOrderResult(true, phoneSoundCallback.getMerchantOrderNo(), phoneSoundCallback.getUpsNo(), BusinessTypeConstants.PhoneSoundPay.getValue());
        } else {
            cardPurchaseService.cardOrderResult(false, phoneSoundCallback.getMerchantOrderNo(), null, null);
        }
    }

    /**
     * 银联二维码回调函数
     *
     * @param response
     * @param request
     */
    @RequestMapping("/unionPayQRCodeCallback")
    public void UnionPayQRCodeCallback(HttpServletResponse response, HttpServletRequest request) {
        //http://106.38.39.137:8080/flight/callback/unionPayQRCodeCallback  银联二维码回调地址
        PaymentCallbackVo paymentCallbackVo = new PaymentCallbackVo();
        String parameter = request.getParameter("billPayment");
        BillPayment parseObject = JSONObject.parseObject(parameter, BillPayment.class);
        paymentCallbackVo.setBillPayment(parseObject);
        paymentCallbackVo.setMid(request.getParameter("mid"));//商户号
        paymentCallbackVo.setTid(request.getParameter("tid"));//终端号
        paymentCallbackVo.setInstMid(request.getParameter("instMid"));//业务类型
        paymentCallbackVo.setBillNo(request.getParameter("billNo"));//账单号
        paymentCallbackVo.setBillQRCode(request.getParameter("billQRCode"));//账单二维码
        paymentCallbackVo.setBillStatus(request.getParameter("billStatus"));//账单状态
        paymentCallbackVo.setBillDesc(request.getParameter("billDesc"));//账单描述
        paymentCallbackVo.setMemberId(request.getParameter("memberId"));//会员号
        paymentCallbackVo.setCounterNo(request.getParameter("counterNo"));//桌号、柜台号、房间号
        paymentCallbackVo.setMerName(request.getParameter("merName"));//商户名称
        paymentCallbackVo.setMemo(request.getParameter("memo"));//付款附言
        paymentCallbackVo.setNotifyId(request.getParameter("notifyId"));//支付通知ID
        paymentCallbackVo.setSecureStatus(request.getParameter("secureStatus"));//担保状态
        paymentCallbackVo.setCompleteAmount(request.getParameter("completeAmount"));//担保完成金额（分）
        paymentCallbackVo.setBillDate(request.getParameter("billDate"));//订单时间，格式yyyy-MM-dd
        paymentCallbackVo.setCreateTime(request.getParameter("createTime"));//账单创建时间，格式yyyy-MM-dd HH:mm:ss
        paymentCallbackVo.setSign(request.getParameter("sign"));//签名
        paymentCallbackVo.setExtraBuyerInfo(request.getParameter("extraBuyerInfo"));//用户额外信息

        if (paymentCallbackVo.getBillStatus().equals("PAID")) {
            cardPurchaseService.cardOrderResult(true, paymentCallbackVo.getBillNo().substring("5676".length()), paymentCallbackVo.getBillNo(), BusinessTypeConstants.UnionQRCodePay.getValue());
        } else {
            cardPurchaseService.cardOrderResult(false, paymentCallbackVo.getBillNo().substring("5676".length()), null, null);
        }

        PrintWriter printWriter;
        response.setCharacterEncoding("UTF-8");
        try {
            printWriter = response.getWriter();
            printWriter.write("SUCCESS");
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 微信小程序支付回调
     *
     * @param resultMap
     */
    @RequestMapping("/wechatPayCallback")
    public void wechatPayCallback(HttpServletResponse response, @RequestBody Map<String, String> resultMap) throws IOException {
        String resXml = "";
        boolean result = payService.isPaySuccessful(resultMap);
        System.out.println("回调成功**************************");
        String returnCode = resultMap.put("return_code", resultMap.get("return_code"));
        String resultCode = resultMap.put("result_code", resultMap.get("result_code"));
        String outTradeNo = resultMap.put("out_trade_no", resultMap.get("out_trade_no"));
        String transaction_id = resultMap.put("transaction_id", resultMap.get("transaction_id"));
        if (result) {
            if (returnCode.equals("SUCCESS") && resultCode.equals("SUCCESS")) {//交易成功
                if (outTradeNo != null) {//商户订单号

                    cardPurchaseService.cardOrderResult(true, outTradeNo, transaction_id, BusinessTypeConstants.Wechat.getValue());

                    //通知微信服务器已经支付成功
                    resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                            + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                }
            }
        } else {
            cardPurchaseService.cardOrderResult(false, outTradeNo, null, null);
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        response.setContentType("text/xml");
        response.getWriter().println(resXml);
    }

    /**
     * 银联二维码退款回调
     *
     * @param response
     * @param request
     */
    @RequestMapping("/flightRefund")
    public void flightRefund(HttpServletResponse response, HttpServletRequest request) {
        String billNo = request.getParameter("billNo"); //账单号
        String refundStatus = request.getParameter("refundStatus"); //退款结果（SUCCESS成功 FAIL失败 PROCESSING处理）
        FinanceOrderRefundment refundment = new FinanceOrderRefundment();
        refundment.setOrderId(billNo);
        refundment.setOrderTypeId(2L);
        List<FinanceOrderRefundment> refundments = financeOrderRefundmentService.selectFinanceOrderRefundmentList(refundment);
        if (refundStatus.equals("SUCCESS")) {
            FinanceOrderRefundment orderRefundment = refundments.get(0);
            orderRefundment.setStatus(String.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.complete.toString()));
            orderRefundment.setReturnTime(new Date());
            financeOrderRefundmentService.updateFinanceOrderRefundment(orderRefundment);
            FlightOrderInfo flightOrderInfo = new FlightOrderInfo();
            flightOrderInfo.setOrderId(Long.valueOf(orderRefundment.getOrderId()));
            flightOrderInfo.setStatus(String.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.complete.toString()));
            remoteFlightService.edit(flightOrderInfo);
            PrintWriter printWriter;
            response.setCharacterEncoding("UTF-8");
            try {
                printWriter = response.getWriter();
                printWriter.write("success");
                printWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (refundStatus.equals("FAIL")) {
            FinanceOrderRefundment orderRefundment = refundments.get(0);
            orderRefundment.setStatus(String.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.refundFailed.toString()));
            financeOrderRefundmentService.updateFinanceOrderRefundment(orderRefundment);
            FlightOrderInfo flightOrderInfo = new FlightOrderInfo();
            flightOrderInfo.setOrderId(Long.valueOf(orderRefundment.getOrderId()));
            flightOrderInfo.setStatus(String.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.refundFailed.toString()));
            remoteFlightService.edit(flightOrderInfo);
            PrintWriter printWriter;
            response.setCharacterEncoding("UTF-8");
            try {
                printWriter = response.getWriter();
                printWriter.write("SUCCESS");
                printWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 鼎盛保险开保回调
     */
    @RequestMapping("heydayCallback")
    public void heydayCallback(@RequestBody HeydayCallback heydayVo, HttpServletResponse response, HttpServletRequest request) {
//        HeydayVo heydayVo = JSONObject.parseObject(request.toString(), HeydayVo.class);

        Map<String, String[]> mRequestMap = request.getParameterMap();
        InsuranceRecord insuranceRecord = new InsuranceRecord();

        AssistProduct assistProduct = assistProductMapper.assistProductByName(heydayVo.getProductName());
        if (assistProduct != null) {
            insuranceRecord.setInsTypeId(assistProduct.getProductTypeid());

            InsuranceType insuranceType = insuranceTypeMapper.selectInsuranceType(assistProduct.getConvertId());
            if (insuranceType != null) {
                insuranceRecord.setInsCoId(insuranceType.getCompanyId());
            }
        }

        Customer customer = customerMapper.selectCustomerByContractPhoneOnes(heydayVo.getPolicyList().get(0).getPolicyMobile());
        if (customer != null) {
            insuranceRecord.setCustomerId(customer.getCustomerId());
        }

        insuranceRecord.setEmployeeId(10l);

//        if (heydayVo.getInsuredList().get(0).getInsuredCrtificatesType().equals("1")){
//            insuranceRecord.setIdTypeId(EmHelper.CertificateType.ID_CARD.getValue());
//        }
//        else if (heydayVo.getInsuredList().get(0).getInsuredCrtificatesType().equals("2")){
//            insuranceRecord.setIdTypeId(EmHelper.CertificateType.PASSPORT.getValue());
//        }
//        else if (heydayVo.getInsuredList().get(0).getInsuredCrtificatesType().equals("3")){
//            insuranceRecord.setIdTypeId(EmHelper.CertificateType.OTHER.getValue());
//        }
//        else if (heydayVo.getInsuredList().get(0).getInsuredCrtificatesType().equals("4")){
//            insuranceRecord.setIdTypeId(EmHelper.CertificateType.ACCOUNT_BOOK.getValue());
//        }
//        else if (heydayVo.getInsuredList().get(0).getInsuredCrtificatesType().equals("5")){
//            insuranceRecord.setIdTypeId(EmHelper.CertificateType.MILITARY_ID.getValue());
//        }
//        else if (heydayVo.getInsuredList().get(0).getInsuredCrtificatesType().equals("6")){
//            insuranceRecord.setIdTypeId(EmHelper.CertificateType.DRVING_LICENSE.getValue());
//        }
//
//        String applicationDate = heydayVo.getApplicationDate();
//        String date = applicationDate.substring(0, 4);
//        date = date + "-" + applicationDate.substring(4, 6);
//        date = date + "-" + applicationDate.substring(6, 8);
//        date = date + " " + applicationDate.substring(8, 10);
//        date = date + ":" + applicationDate.substring(10, 12);
//        date = date + ":" + applicationDate.substring(12, 14);
//        date = date + ":" + applicationDate.substring(14);
//
//        insuranceRecord.setInsCoverName(date);
//
//        String effectedDate = heydayVo.getEffectedDate();
//        String effected = effectedDate.substring(0, 4);
//        effected = effected + "-" + effectedDate.substring(4, 6);
//        effected = effected + "-" + effectedDate.substring(6, 8);
//        effected = effected + " " + effectedDate.substring(8, 10);
//        effected = effected + ":" + effectedDate.substring(10, 12);
//        effected = effected + ":" + effectedDate.substring(12, 14);
//        effected = effected + ":" + effectedDate.substring(14);
//
//        String overDate = heydayVo.getOverDate();
//        String over = overDate.substring(0, 4);
//        over = over + "-" + overDate.substring(4, 6);
//        over = over + "-" + overDate.substring(6, 8);
//        over = over + " " + overDate.substring(8, 10);
//        over = over + ":" + overDate.substring(10, 12);
//        over = over + ":" + overDate.substring(12, 14);
//        over = over + ":" + overDate.substring(14);
//
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        try {
//            insuranceRecord.setInsValidDate(format.parse(effected));
//            insuranceRecord.setInsInvalidDate(format.parse(over));
//        } catch (Exception e){
//            System.out.println("日期转换错误");
//        }
//        insuranceRecord.setInsured(heydayVo.getInsuredList().get(0).getInsuredName());
//        insuranceRecord.setBeneficiary(heydayVo.getBeneficiaryList().get(0).getBeneficiaryName());
//        if (heydayVo.getOrderState().equals("SUCCESS")){
//            insuranceRecord.setInsMemo("已开通成功");
//            insuranceRecord.setElectronInsNo(heydayVo.getPolicyNo());
//        }
//        else {
//            insuranceRecord.setInsMemo("开通失败");
//        }
//        Date time = new Date();
//        insuranceRecord.setOperationTime(format.format(time));
//        insuranceRecord.setInsCertificateNo(heydayVo.getInsuredList().get(0).getInsuredCertificatesNum());
//        insuranceRecord.setMobilephone(heydayVo.getInsuredList().get(0).getInsuredMobile());
//        insuranceRecord.setOrderNum(heydayVo.getOrderNo());
//        insuranceRecord.setOrderSource(EmHelper.businessType.FLIGHT.getValue());
//        insuranceRecordMapper.insertInsuranceRecord(insuranceRecord);
//        System.out.println(request);
    }
}
